const { Service } = require('egg')
const { tableToList, zc } = require('../utils/tools')
// const cheerio = require('cheerio');
const time = [] // 记录每节课上课时间

module.exports = class CourseService extends Service {
  /**
   * * 学生个人课表查询
   * @param {string} term 学期
   * @return {Object} *
   */
  async table(term) {
    // eslint-disable-next-line no-unused-vars, prefer-const, @typescript-eslint/no-unused-vars
    let [xnm, _, xqm] = term ? term.split('-') : ['', '', '']
    if (term) { xqm = xqm === '1' ? '3' : '12' }
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Host: 'jw.hieu.edu.cn',
        Origin: 'http://jw.hieu.edu.cn',
      },
      data: {
        xnm,
        xqm,
        kzlx: 'ck',
        xsdm: '',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = JSON.parse(res.data.toString())
        const note = tableList.sjkList// 提取备注
        for (const key in tableList) {
          if (key !== 'kbList') {
            delete tableList[key]
          }
        }
        // 开始处理
        const data = tableList.kbList
        if (data === undefined) { // 判断是否有数据
          return { table: {}, time, note: '' }
        }
        for (const i of data) {
          for (const key in i) {
            if (key !== 'jxbmc' && key !== 'xm' && key !== 'jc' && key !== 'cdmc' && key !== 'zcd' && key !== 'xqjmc') { // 删除多余信息
              delete i[key]
            }
          }
          if (i.zcd.match(/,/)) {
            if (i.zcd.match(/\(/g)) { // 处理周次
              const newStr = i.zcd.replace('周(', '(')
              i.P = zc(newStr)
            } else {
              const newStr = i.zcd.replace('周,', ',')
              i.P = zc(newStr)
            }
          } else {
            i.P = zc(i.zcd)
          }
          i.j = i.jc.replace('节', '周')// 将上课节数遍历出来
          i.Jc = zc(i.j)
        }
        const newData = data.map((item) => ({ // 改变建值
          N: item.jxbmc,
          T: item.xm,
          R: item.cdmc,
          W: item.zcd,
          P: item.P,
          X: item.jc,
          Week: item.xqjmc,
          J: item.Jc,
        }))
        const rows = 12
        const cols = 7
        const table = Array.from({ length: rows }, () => Array(cols).fill(null).map(() => []))// 构建一个表格，课表表格
        const weekMap = { // 使用weekMap保存星期的映射关系
          星期一: 0,
          星期二: 1,
          星期三: 2,
          星期四: 3,
          星期五: 4,
          星期六: 5,
          星期日: 6,
        }
        for (let j = 0; j < newData.length; j++) {
          const temp = newData[j]
          const dayIndex = weekMap[temp.Week]

          for (let i = 0; i < temp.J.length; i++) {
            const v = parseInt(temp.J[i])
            if (dayIndex !== undefined) { // 确保 dayIndex 存在，即 temp.Week 是一个有效的星期几
              table[v][dayIndex].push(temp)
            } else {
              console.error(`Invalid week day: ${temp.Week}`)
            }
          }
        }
        for (const i of table) { // 删掉临时多余属性
          for (let j = 0; j < i.length; j++) {
            for (const k of i[j]) {
              for (const key in k) {
                if (key === 'X' || key === 'Week' || key === 'J') {
                  delete k[key]
                }
              }
            }
          }
        }
        const dataJson = {}
        for (let i = 1; i < table.length; i++) { // 构建json对象
          dataJson[i] = table[i]
        }

        // 结束处理

        let notedata = ''
        for (const i in note) {
          for (const key in note[i]) {
            if (key !== 'qtkcgs') {
              delete note[i][key]
            }
          }
          notedata += note[i].qtkcgs
        }
        return { table: dataJson, time, note: notedata }
      }
      catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, time: [], note: '' }
  }

  /**
   * * 班级课表查询
   * @param {string} term 学期
   * @param {{label:string, value:string}} yx 院系
   * @param {{label:string, value:string}} nj 年级
   * @param {{label:string, value:string}} zy 专业
   * @param {{label:string, value:string}} name 班级
   * @return {object} *
   */

  async Ctable(term, yx, nj, zy, name) {
    const [xnm, _, xqm] = term ? term.split('-') : ['', '', '']
    let xqm2 = ''
    const xnmc = `${xnm}-${_}`
    if (term) { xqm2 = xqm === '1' ? '3' : '12' }
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jwglxt/kbdy/bjkbdy_cxBjKb.html?gnmkdm=N214505`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnm,
        xqm: xqm2,
        xnmc,
        xqmmc: xqm,
        xqh_id: '0009F242E1F140C48A0F6EBCDFBEDB7F',
        njdm_id: nj.value,
        zyh_id: zy.value,
        bh_id: name.value,
        tjkbzdm: '1',
        tjkbzxsdm: '0',
        zymc: zy,
        jgmc: yx,
        njmc: nj,
        bj: name,
        // xkrs: '43', // 选课人数，此参数不传也可以
        jsxm: '',
        lxdh: '',
        bh: name.value,
        zs: '',
        zxszjjs: 'false',
        xsdm: '',
        kclxdm: '',
        kzlx: 'ck',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Host: 'jw.hieu.edu.cn',
        Origin: 'http://jw.hieu.edu.cn',
      },
      timeout: 10000,
    })
    const info = {}
    if (res.status === 200) {
      try {
        const pageXml = res.data.toString()
        const pageObj = JSON.parse(pageXml) // 将字符串解析为 JavaScript 对象
        const data = pageObj.kbList // 提取 kbList
        if (data === undefined || data.length === 0) { // 判断是否有数据
          return { table: {}, header: [] }
        }
        for (const i of data) {
          for (const key in i) {
            if (key !== 'jxbmc' && key !== 'xm' && key !== 'jc' && key !== 'cdmc' && key !== 'zcd' && key !== 'xqjmc') { // 删除多余信息
              delete i[key]
            }
          }
          if (i.zcd.match(/,/)) {
            if (i.zcd.match(/\(/g)) { // 处理周次
              const newStr = i.zcd.replace('周(', '(')
              i.P = zc(newStr)
            } else {
              const newStr = i.zcd.replace('周,', ',')
              i.P = zc(newStr)
            }
          } else {
            i.P = zc(i.zcd)
          }
          i.j = i.jc.replace('节', '周')
          i.Jc = zc(i.j)
        }
        const newData = data.map((item) => ({ // 改变建值
          N: item.jxbmc,
          T: item.xm,
          R: item.cdmc,
          W: item.zcd,
          P: item.P,
          X: item.jc,
          Week: item.xqjmc,
          J: item.Jc,
        }))
        const rows = 12
        const cols = 7
        const table = Array.from({ length: rows }, () => Array(cols).fill(null).map(() => [])) // 创建一个二维数组，用于存储课表数据，构建一个表格
        let x = 1
        table[0][1].push(x)
        x = 2
        table[0][1].push(x)

        const weekMap = { // 使用weekMap保存星期的映射关系
          星期一: 0,
          星期二: 1,
          星期三: 2,
          星期四: 3,
          星期五: 4,
          星期六: 5,
          星期日: 6,
        }
        for (let j = 0; j < newData.length; j++) {
          const temp = newData[j]
          const dayIndex = weekMap[temp.Week]

          for (let i = 0; i < temp.J.length; i++) {
            const v = parseInt(temp.J[i])
            if (dayIndex !== undefined) { // 确保 dayIndex 存在，即 temp.Week 是一个有效的星期几
              table[v][dayIndex].push(temp)
            } else {
              console.error(`Invalid week day: ${temp.Week}`)
            }
          }
        }
        for (const i of table) { // 删除周次节次信息
          for (let j = 0; j < i.length; j++) {
            for (const k of i[j]) {
              for (const key in k) {
                if (key === 'X' || key === 'Week' || key === 'J') {
                  delete k[key]
                }
              }
            }
          }
        }
        const dataJson = {}
        for (let i = 1; i < table.length; i++) { // 构建json对象
          dataJson[i] = table[i]
        }
        return { table: dataJson, time: [], note: '' }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return info
  }

  /**
   * * 教师课表查询
   * @param {string} term 学期
   * @param {string} yx 院系
   * @param {string} name 教师姓名
   * @return {Array} *
   */
  async Ttable(term, yx, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_teacher_ifr`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnxqh: term,
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
        skyx: yx,
        jszc: '',
        skbjid: '',
        skjs: name,
        zc1: '',
        zc2: '',
        skxq1: '',
        skxq2: '',
        jc1: '',
        jc2: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable')
        return tableList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return []
  }

  /**
   * * 教室课表查询
   * @param {string} term 学期
   * @param {string} building 教学楼
   * @param {string} name 教室名称
   * @return {Array} *
   */
  async Rtable(term, building, name) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbcx/kbxx_classroom_ifr`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xnxqh: term,
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
        skyx: '',
        xqid: '',
        jzwid: building,
        gnq: '',
        jszc: '',
        skbjid: '',
        skjs: name,
        zc1: '',
        zc2: '',
        skxq1: '',
        skxq2: '',
        jc1: '',
        jc2: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#kbtable')
        return tableList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return []
  }
}
